package com.example.coroutines

import kotlinx.coroutines.*
import org.junit.Test


/**
 * 协程上下文测试
 * 说明：子协程会创建一个全新的Job
 *
 * @author zhouronghua
 * @time 2022/1/1 9:23 上午
 */
class CoroutineContextTest {

    /**
     * 测试协程作用域继承
     * 继承的子协程：Job新创建，协程名称，调度器都是与父协程相同
     *
     * @author zhouronghua
     * @time 2022/1/1 9:43 上午
     */
    @Test
    fun test_coroutine_context_extend() = runBlocking {
        val scope = CoroutineScope(
            Job() + Dispatchers.IO + CoroutineName("我的协程")
        )
        // 创建一个新的协程
        val job = scope.launch {
            println("${coroutineContext[Job]}  ${Thread.currentThread().name}")
            async {
                println("child coroutine ${coroutineContext[Job]}  ${coroutineContext[CoroutineName]} ${Thread.currentThread().name}")
                "子协程完成"
            }.await()
        }
        job.join()
    }
}